package cn.yj.frame.event;

import cn.yj.frame.netty.NettyServer;
import cn.yj.register.RegisterConfig;
import org.springframework.boot.context.event.ApplicationContextInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;

import java.net.InetSocketAddress;

/**
 * 在上下文初始化的时候注册服务
 * @author 永健
 * @since 2022-01-19 10:23
 */
public class ApplicationStartingListener implements ApplicationListener<ApplicationContextInitializedEvent> {

    @Override
    public void onApplicationEvent(ApplicationContextInitializedEvent applicationContextInitializedEvent) {
        ConfigurableEnvironment env = applicationContextInitializedEvent.getApplicationContext().getEnvironment();
        String host = env.getProperty("spring.rpc.provider.host");
        String applicationName = env.getProperty("spring.application.name");
        if ("".equals(host) || host == null) {
            return;
        }
        String[] split = host.split(":");
        InetSocketAddress inetSocketAddress = new InetSocketAddress(split[0], Integer.parseInt(split[1]));
        // 启动netty，提供者服务启动，注册服务
        RegisterConfig.register(applicationName, host);
        new NettyServer().start(inetSocketAddress);
    }
}
